/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.topo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.TopuConfCache;
import com.sinodata.bsm.center.cache.TopuPlayOrderCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.relation.ResRelationService;
import com.sinodata.bsm.center.service.resource.ResViewService;
import com.sinodata.bsm.center.service.topo.TopoService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.TopoConstants;
import com.sinodata.bsm.common.vo.Property;
import com.sinodata.bsm.common.vo.RelationType;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResType;
import com.sinodata.bsm.common.vo.ResTypeTooltip;
import com.sinodata.bsm.common.vo.ResView;
import com.sinodata.bsm.common.vo.ResViewRel;
import com.sinodata.bsm.common.vo.TopuConf;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author sunxiangxue
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-10 下午2:42:04          sunxiangxue        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class TopoAction extends BaseAction {

    Logger logger = Logger.getLogger(TopoAction.class);

    private TopuConf topuConf;

    @Autowired
    private TopoService topoService;

    @Autowired
    private TopuConfCache topuConfCache;//拓扑缓存对象

    @Autowired
    private ResViewService resViewService;

    @Autowired
    private ResRelationService resRelationService;

    @Autowired
    private TopuPlayOrderCache topuPlayOrderCache;

    private Long resTypeId;

    private String fileType;

    private String id;//资源树中使用的ID，结构为：节点类型|资源ID|父节点ID

    private Long viewId;//视图ID

    private Long mainEventId;//主事件ID

    public Long getMainEventId() {
        return mainEventId;
    }

    public void setMainEventId(Long mainEventId) {
        this.mainEventId = mainEventId;
    }

    public String getId() {
        return id;
    }

    public Long getViewId() {
        return viewId;
    }

    public void setViewId(Long viewId) {
        this.viewId = viewId;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public Long getResTypeId() {
        return resTypeId;
    }

    public void setResTypeId(Long resTypeId) {
        this.resTypeId = resTypeId;
    }

    public TopuConf getTopuConf() {
        return topuConf;
    }

    public void setTopuConf(TopuConf topuConf) {
        this.topuConf = topuConf;
    }

    private long resourceTypeId;//资源类型ID

    public String getTopoTreeData() {
        return topoTreeData;
    }

    public void setTopoTreeData(String topoTreeData) {
        this.topoTreeData = topoTreeData;
    }

    private long resourceId;//资源ID

    private List<Long> resourceIds;

    private String topoTreeData;

    public List<Long> getResourceIds() {
        return resourceIds;
    }

    public void setResourceIds(List<Long> resourceIds) {
        this.resourceIds = resourceIds;
    }

    public long getResourceId() {
        return resourceId;
    }

    public void setResourceId(long resourceId) {
        this.resourceId = resourceId;
    }

    private String resourceImagePath;//资源图片路径

    public String getResourceImagePath() {
        return resourceImagePath;
    }

    public void setResourceImagePath(String resourceImagePath) {
        this.resourceImagePath = resourceImagePath;
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    @Override
    public Object getModel() {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#list()
     */
    @Action("my-list")
    @Override
    public String list() throws Exception {
        try {
            List<TopuConf> list = topoService.findByCatalogId(topuConf.getCatalogId());
            JSONArray jsonArray = JSONArray.fromObject(list);
            response.getWriter().write(jsonArray.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询拓扑列表失败。", e);
        }
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#save()
     */
    @Override
    public String save() throws Exception {
        logger.debug("parameters sends to save:" + topuConf.toString());
        topoService.saveOrUpdate(topuConf);
        topuConfCache.put(topuConf);
        TopuConf topuConfTmp = new TopuConf();
        topuConfTmp.setId(topuConf.getId());
        JSONObject jsonObject = JSONObject.fromObject(topuConfTmp);
        Struts2Utils.renderJson(jsonObject.toString());
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#delete()
     */
    @Override
    public String delete() throws Exception {
        if (topuConf == null) {
            logger.info("parameters 'topuConf' is null:");
            return null;
        }
        logger.debug("parameters sends to delete:" + topuConf.toString());
        Long topoId = topuConf.getId();
        topoService.delete(topoId);
        topuConfCache.remove(topoId);
        topuPlayOrderCache.removeByTopoId(topoId);
        renderText(SUCCESS);
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public String execute() throws Exception {
        return null;
    }

    public long getResourceTypeId() {
        return resourceTypeId;
    }

    public void setResourceTypeId(long resourceTypeId) {
        this.resourceTypeId = resourceTypeId;
    }

    public String findNormByResourceId() {
        List<Property> list = topoService.findNormByResourceId(resourceId);
        JSONArray jsonArray = JSONArray.fromObject(list);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 查询所有资源图片
     */
    public String findAllResourceImage() {
        List<String> list = new ArrayList<String>();
        String contextPath = request.getSession().getServletContext().getRealPath("");
        String resImagePath = contextPath + TopoConstants.TOPO_RES_IMAGE_PATH;
        File file = new File(resImagePath);
        File[] fileArr = file.listFiles();
        for (File imageFile : fileArr) {
            if (imageFile.isFile()) {
                list.add(TopoConstants.TOPO_RES_IMAGE_PATH + imageFile.getName());
            }

        }
        JSONArray jsonArray = JSONArray.fromObject(list);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    public String findAllBgImageResult() {
        List<String> list = new ArrayList<String>();
        String contextPath = request.getSession().getServletContext().getRealPath("");
        String resImagePath = contextPath + TopoConstants.TOPO_BG_IMAGE_PATH;
        File file = new File(resImagePath);
        File[] fileArr = file.listFiles();
        for (File imageFile : fileArr) {
            if (imageFile.isFile()) {
                list.add(TopoConstants.TOPO_BG_IMAGE_PATH + imageFile.getName());
            }

        }
        JSONArray jsonArray = JSONArray.fromObject(list);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    public void uploadFile() {
        String path = "";
        if (TopoConstants.FILE_TYPE_TOPO_BG.equals(fileType)) {
            path = TopoConstants.TOPO_BG_IMAGE_PATH;
        } else if (TopoConstants.FILE_TYPE_RES.equals(fileType)) {
            path = TopoConstants.TOPO_RES_IMAGE_PATH;
        }
        if (path == null || "".equals(path))
            return;

        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();
        Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
        while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
            // get the value of this input tag     
            String inputName = (String) fileParameterNames.nextElement();

            // get the content type     
            String[] contentType = multiWrapper.getContentTypes(inputName);

            if (isNonEmpty(contentType)) {
                // get the name of the file from the input tag     
                String[] fileName = multiWrapper.getFileNames(inputName);

                if (isNonEmpty(fileName)) {
                    // Get a File object for the uploaded File     
                    File[] files = multiWrapper.getFiles(inputName);
                    if (files != null) {
                        for (int index = 0; index < files.length; index++) {
                            String contextPath = request.getSession().getServletContext().getRealPath("");
                            String uploadPath = contextPath + path + fileName[index];
                            File dstFile = new File(uploadPath);
                            this.copy(files[index], dstFile);
                        }
                    }
                }
            }
        }

    }

    private void copy(File src, File dst) {
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new BufferedInputStream(new FileInputStream(src), TopoConstants.BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst), TopoConstants.BUFFER_SIZE);
            byte[] buffer = new byte[TopoConstants.BUFFER_SIZE];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static boolean isNonEmpty(Object[] objArray) {
        boolean result = false;
        for (int index = 0; index < objArray.length && !result; index++) {
            if (objArray[index] != null) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 空方法，为了长期保持session而用。
     * @return
     */
    public String keepSession() {
        request.getSession().setAttribute("keepTopoSession", System.currentTimeMillis());
        return null;
    }

    /**
     * 查询拓扑图资源状态
     * @return
     */
    public String findTopoResourceStatus() {
        if (resourceIds == null)
            return null;
        logger.debug("size of parameters sends to findTopoResourceStatus:" + resourceIds.size());
        //为了长期保持session而用。
        request.getSession().setAttribute("findTopoResourceStatus", System.currentTimeMillis());
        JSONArray jsonArray = topoService.findTopoResourceStatus(resourceIds);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;

    }

    public String findTopoById() throws UnsupportedEncodingException {
        if (topuConf == null || topuConf.getId() == null)
            return null;
        logger.debug("parameters sends to findTopoById---:" + topuConf.getId());
        topuConf = topoService.findById(topuConf.getId());
        Struts2Utils.renderJson(topuConf);
        return null;
    }

    /**
     * 初始化拓扑树。
     * @return
     */
    public String initTopoTree() {
        /*获取该用户可访问的拓扑图集合*/
        boolean canManageTopo = UserFunctionValidate.sysFunctionValidate(FunctionConstants.TOPO_MANAGER);
        logger.debug("current user topo manage purView =" + canManageTopo);
        List<Long> topoIdList = UserFunctionValidate.getTopoIdListForUser();
        JSONArray jsonArray = topoService.initTopoTree(topoIdList, canManageTopo);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 获取当前用户是否有拓扑编辑权限
     */
    public void findTopoManagePurview() {
        boolean canManageTopo = UserFunctionValidate.sysFunctionValidate(FunctionConstants.TOPO_MANAGER);
        Struts2Utils.renderText((new Boolean(canManageTopo)).toString());
    }

    /**
     * 修改名称
     * @return
     * @throws Exception
     */
    public String updateName() throws Exception {
        //保存要修改的属性值
        String newName = topuConf.getName();
        Long resId = topuConf.getResId();
        logger.debug("parameters sends to updateName:" + topuConf.toString());
        //查询缓存
        topuConf = topoService.findById(topuConf.getId());
        //复制bean
        TopuConf newTopuConf = new TopuConf();
        BeanUtils.copyProperties(newTopuConf, topuConf);
        //更新数据库
        newTopuConf.setName(newName);
        newTopuConf.setResId(resId);//防止copy时将null值copy成了0.
        topoService.saveOrUpdate(newTopuConf);
        //更新缓存
        topuConfCache.put(newTopuConf.getId(), newTopuConf);
        renderText(SUCCESS);
        return null;
    }

    /**
     * 修改拓扑信息
     * @return
     * @throws Exception
     */
    public String updateTopoXml() throws Exception {
        //保存要修改的属性值
        Long resId = topuConf.getResId();
        logger.debug("resId sends to findTopoResourceStatus:" + topuConf.toString());
        String xml = topuConf.getXml();
        //查询缓存
        topuConf = topoService.findById(topuConf.getId());
        Long catalogId = topuConf.getCatalogId();
        if (catalogId == null)
            return null;
        //复制bean
        TopuConf newTopuConf = new TopuConf();
        BeanUtils.copyProperties(newTopuConf, topuConf);
        newTopuConf.setResId(resId);
        newTopuConf.setXml(xml);
        topoService.saveOrUpdate(newTopuConf);
        topuConfCache.put(newTopuConf);
        Struts2Utils.renderText("success");
        return null;
    }

    public String findAllRelationType() {
        List<RelationType> list = topoService.findAllRelationType();
        JSONArray jsonArray = JSONArray.fromObject(list);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    public String findToolTipInfoByRelationId() throws UnsupportedEncodingException {
        Res res = topoService.findResByResId(resourceId);
        if (res == null)
            return null;
        ResTypeTooltip resTypeTooltip = topoService.findToolTipInfoByRelationId(res.getResTypeId());
        if (resTypeTooltip == null)
            return null;
        Struts2Utils.renderXml(resTypeTooltip.getTooltipInfo());
        return null;
    }

    public String findAllResourceType() {
        List<ResType> list = topoService.findAllResourceType();
        JSONArray jsonArray = JSONArray.fromObject(list);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 查询子网内容
     * @return
     */
    public String findTopoByResId() {
        logger.debug("parameters sends to findTopoByResId:resourceId=" + resourceId);
        List<TopuConf> list = topoService.findTopoByResId(resourceId);
        JSONArray jSONArray = new JSONArray();
        JSONObject jsonObject = null;
        //播放的拓扑图
        for (TopuConf topuConf : list) {
            jsonObject = new JSONObject();
            jsonObject.element("id", topuConf.getId());
            jsonObject.element("name", topuConf.getName());
            jsonObject.element("xml", topuConf.getXml());
            jsonObject.element("type", "0");//拓扑图。因为首页也展现性能图，所以需要该字段。
            jSONArray.add(jsonObject);
        }
        Struts2Utils.renderJson(jSONArray.toString());
        return null;
    }

    private Map<String, Integer> statusMap = null;

    public String resViewTree() throws Exception {
        ResView[] viewList = resViewService.findAll();

        Map<String, Integer> smap = new HashMap<String, Integer>();
        Set<Long> relationTypesIds = findRelationTypeIds();
        this.statusMap = smap;
        if (id == null) {
            JSONArray jsonArray = new JSONArray();
            for (ResView view : viewList) {
                JSONObject json = genResViewNode(view);
                List<ResViewRel> viewRelList = resViewService.getResViewRelByViewId(view.getId());

                if (viewRelList != null) {
                    JSONArray cArray = new JSONArray();
                    for (ResViewRel rel : viewRelList) {
                        if (ResBean.get(rel.getResId()) == null || ResBean.get(rel.getResId()).res() == null)
                            continue;
                        JSONObject rootJson = genResNode(ResBean.get(rel.getResId()).res(), 0L, relationTypesIds);
                        loadLevel(rootJson, 1, 1, relationTypesIds);
                        cArray.add(rootJson);

                    }
                    json.element("children", cArray);
                }

                jsonArray.add(json);

            }
            Struts2Utils.renderText(jsonArray.toString());
        } else {
            String[] idArray = this.id.split("[|]");
            JSONArray children = loadChildNode(Long.parseLong(idArray[1]), relationTypesIds);
            Struts2Utils.renderText(children.toString());
        }

        return null;
    }

    private Set<Long> findRelationTypeIds() {

        Set<RelationType> relationTypes = resRelationService.getSelfAndSubRelationType();
        Set<Long> relationTypesIds = new HashSet<Long>();
        for (RelationType type : relationTypes) {
            relationTypesIds.add(type.getId().longValue());
        }
        return relationTypesIds;
    }

    private JSONObject genResViewNode(ResView view) {
        JSONObject json = new JSONObject();
        json.element("id", "1|" + view.getId() + "|0");
        json.element("name", view.getName());
        json.element("open", true);
        json.element("nocheck", true);
        return json;
    }

    private void loadLevel(JSONObject resjson, int expandLevel, int level, Set<Long> relationTypesIds) {
        try {
            if (expandLevel == level) {
                return;
            }
            resjson.element("open", true);
            level++;
            String[] idArr = resjson.getString("id").split("[|]");
            JSONArray children = loadChildNode(Long.parseLong(idArr[1]), relationTypesIds);
            resjson.element("children", children);
            for (int i = 0; i < children.size(); i++) {
                JSONObject obj = children.getJSONObject(i);
                if (idArr[0].equals("3")) {
                    JSONArray resJsons = obj.getJSONArray("children");
                    for (int k = 0; k < resJsons.size(); k++) {
                        JSONObject res = resJsons.getJSONObject(k);
                        loadLevel(res, expandLevel, level, relationTypesIds);
                    }
                } else {
                    loadLevel(obj, expandLevel, level, relationTypesIds);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    private JSONObject genResNode(Res res, Long parentResId, Set<Long> relationTypesIds) {
        JSONObject json = new JSONObject();
        json.element("id", "2|" + res.getId() + "|" + parentResId);
        json.element("name", res.getName());

        int status = res.getPaused() == 1 ? 0 : res.getHealthStatus();
        json.element("iconSkin", "res" + status);
        statusMap.put("2|" + res.getId() + "|" + parentResId, status);
        json.element("isParent", resRelationService.hasChild(res.getId(), relationTypesIds));
        json.element("resTypeId", res.getResTypeId());
        return json;
    }

    private JSONArray loadChildNode(Long parentResId, Set<Long> relationTypesIds) {
        List<List<ResBean>> types = children(parentResId);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < types.size(); i++) {
            List<ResBean> type = types.get(i);
            if (type.size() == 1) {
                JSONObject childRes = genResNode(type.get(0).res(), parentResId, relationTypesIds);
                jsonArray.add(childRes);
            } else {
                JSONArray childArray = new JSONArray();
                int maxStatus = 0;
                int pausedSize = 0;
                for (int j = 0; j < type.size(); j++) {
                    Res cRes = type.get(j).res();
                    if (cRes.getHealthStatus() > maxStatus) {
                        maxStatus = cRes.getHealthStatus();
                    }
                    if (cRes.getPaused() == 1) {
                        pausedSize++;
                    }
                    JSONObject childRes = genResNode(cRes, parentResId, relationTypesIds);
                    childArray.add(childRes);
                }
                boolean showTypeNode = true;
                if (showTypeNode) {
                    ResTypeBean resTypeBean = type.get(0).type();
                    JSONObject typeNode = genResTypeNode(resTypeBean.resType(), parentResId);
                    int status = type.size() == pausedSize ? 0 : maxStatus;
                    typeNode.element("iconSkin", "type" + status);
                    statusMap.put("3|" + resTypeBean.resType().getId() + "|" + parentResId, status);
                    typeNode.element("children", childArray);
                    jsonArray.add(typeNode);
                } else {
                    jsonArray.addAll(childArray);
                }
            }
        }
        return jsonArray;
    }

    private List<List<ResBean>> children(Long parentResId) {
        List<ResBean> children = RelationHelper.children(parentResId);
        List<List<ResBean>> types = new ArrayList<List<ResBean>>();
        for (ResBean child : children) {
            List<ResBean> type = null;
            for (int j = 0; j < types.size(); j++) {
                if (types.get(j).get(0).res().getResTypeId().longValue() == child.res().getResTypeId().longValue()) {
                    type = types.get(j);
                    break;
                }
            }
            if (type == null) {
                type = new ArrayList<ResBean>();
                types.add(type);
            }
            type.add(child);
        }
        return types;
    }

    private JSONObject genResTypeNode(ResType resType, Long resId) {
        JSONObject json = new JSONObject();
        json.element("id", "3|" + resType.getId() + "|" + resId);
        json.element("name", resType.getName());
        json.element("isParent", true);
        return json;
    }

    /**
     * 通过视图ID查询资源树节点信息。
     * @return
     */
    public String findResByViewId() {
        List<ResViewRel> list = resViewService.getResViewRelByViewId(viewId);
        if (list == null)
            return null;
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        Res res = null;
        for (ResViewRel resViewRel : list) {
            jsonObject = new JSONObject();
            Long resId = resViewRel.getResId();
            res = topoService.findResByResId(resId);
            if (res == null)
                continue;
            jsonObject.element("id", TopoConstants.PRE_ID_RES + resId);
            jsonObject.element("resTypeId", res.getResTypeId());
            jsonObject.element("name", res.getName());
            jsonArray.add(jsonObject);
        }
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 通过资源类别ID获取资源树节点信息
     * @return
     */
    public String findResByResTypeId() {
        ResBean[] resBeanArr = ResBean.get(resourceId).childrenByType(resTypeId);
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        Res res = null;
        for (ResBean resBean : resBeanArr) {
            res = resBean.res();
            jsonObject = new JSONObject();
            jsonObject.element("id", TopoConstants.PRE_ID_RES + res.getId());
            jsonObject.element("resTypeId", res.getResTypeId());
            jsonObject.element("name", res.getName());
            jsonArray.add(jsonObject);
        }
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 查询首页播放的拓扑集合。
     * @return
     */
    public String findShowTopos() {
        JSONArray jsonArray = topoService.findShowTopos();
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 根据主事件ID查询所有关联事件
     * @return
     */
    public String findAllRelatedEvents() {
        JSONArray jsonArray = topoService.findByMainEvent(mainEventId);
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    /**
     * 判断是否有操作资源的权限。
     * @return
     */
    public String judgePrivilege() {
        boolean hasPrivilege = UserFunctionValidate.resFunctionValidate(resourceId, FunctionConstants.EDIT_RES);
        Struts2Utils.renderJson(hasPrivilege);
        return null;
    }

    /**
     * 复制拓扑图。
     * @return
     * @throws Exception
     */
    public String copyTopo() throws Exception {
        Long id = topuConf.getId();
        String originalXml = topuConfCache.get(id).getXml();
        topuConf.setXml(originalXml);
        topuConf.setId(null);
        topoService.saveOrUpdate(topuConf);
        topuConfCache.put(topuConf);
        //返回新生成的拓扑图ID
        TopuConf topuConfTmp = new TopuConf();
        topuConfTmp.setId(topuConf.getId());
        JSONObject jsonObject = JSONObject.fromObject(topuConfTmp);
        Struts2Utils.renderJson(jsonObject.toString());
        return null;
    }
}
